<template>
  <div class="ep-container">
    <el-form-item :label="options.label" :prop="options.name" :show-message="!isDetail" class="ep-form-item">
      <el-input
        v-if="!isDetail"
        class="ep-amount-container"
        v-model="fieldModel"
        type="text"
        :readonly="options.readonly"
        :placeholder="options.placeholder"
        :min="options.min"
        :max="options.max"
        @input="handleInput"
        @blur="handleBlurEvent(fieldModel)"
      />
      <div v-else class="ep-detail-content">
        {{ fieldModel }}
      </div>
    </el-form-item>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'
import defaultProps from '../props'

const name = 'ep-amount'
Symbol(name)

export default defineComponent({
  name,
  props: defaultProps,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const isDetail = computed(() => props.options.permission > 0)
    const fieldModel = computed({
      get() {
        if (isDetail.value && !props.modelValue) {
          return '--'
        }
        return props.modelValue as string
      },
      set(val: string) {
        emit('update:modelValue', val)
      }
    })

    /** 当number类型时限制输入大小范围 */
    const handleBlurEvent = (value: string) => {
      const limitMin = props.options.min || 0
      const limitMax = props.options.max || 9
      if (value > limitMax) {
        emit('update:modelValue', limitMax)
      }
      if (value < limitMin) {
        emit('update:modelValue', limitMin)
      }

      // 省略末尾的0
      if (props.options.omitEndZero && String(value).indexOf('.') !== -1) {
        const filtered = String(value).replace(/\.?0*$/, '')
        if (filtered !== String(value)) {
          emit('update:modelValue', filtered)
        }
      }
    }

    const handleInput = (value: string) => {
      // 基础过滤：允许数字、负号、单个小数点
      let filtered = value
        .replace(/[^\d.]/g, '') // 只允许数字和小数点
        .replace(/^0+(\d)/, '$1') // 禁止0开头
        .replace(/(\..*)\./g, '$1') // 禁止多个小数点

      // 保留小数位数处理
      if (props.options.decimalPlaces === 2) {
        filtered = filtered.replace(/(\.\d{2})\d+/g, '$1')
      } else {
        filtered = filtered.replace(/(\.\d)\d+/g, '$1')
      }

      if (filtered !== value) {
        emit('update:modelValue', filtered)
      }
    }

    return {
      fieldModel,
      isDetail,
      handleInput,
      handleBlurEvent
    }
  }
})
</script>
